package com.sinacom.ibuilding.service;


import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;


import com.ibatis.dao.client.DaoManager;
import com.sinacom.ibuilding.beans.Attach;
import com.sinacom.ibuilding.beans.Member;
import com.sinacom.ibuilding.beans.Message;
import com.sinacom.ibuilding.beans.Role;
import com.sinacom.ibuilding.beans.Sms;
import com.sinacom.ibuilding.dao.DaoConfig;
import com.sinacom.ibuilding.dao.iface.MessageDao;
import com.sinacom.ibuilding.util.Constants;
import com.sinacom.ibuilding.util.Helper;
import com.sinacom.ibuilding.util.PageModel;

public class MessageService {
	
	private MessageDao messageDao;
	private TransActionService ts = new TransActionService();
	private IdCreateService idService = new IdCreateService();
	private NewsService newsService = new NewsService();
	private MemberService memberService = new MemberService();
	public MessageService(){
		DaoManager	daoManager = DaoConfig.getDaoManager();
		messageDao = (MessageDao) daoManager.getDao(MessageDao.class);
	}
	
	public List getIndexEmail(Member member){
	    if(member == null)return null;
	    Map map = new HashMap();
	    map.put("type",new Integer(Constants.MSG_TYPE_EMAIL));
	    map.put("boxType", new Integer(Constants.MSG_BOX_RECEIVE));
	    map.put("member", member.getId());
	    map.put("startId", new Integer(1));
	    map.put("endId", new Integer(5));
	    return messageDao.getMessageList(map);
	}
	
	public PageModel getMailReceiveBox(Member member,int page){
		if(member == null) return null;
		int pageSize = 13;
	    Map map = new HashMap();
	    map.put("type",new Integer(Constants.MSG_TYPE_EMAIL));
	    map.put("boxType", new Integer(Constants.MSG_BOX_RECEIVE));
	    map.put("member", member.getId());
	    int startId = (page-1) * pageSize + 1; 
	    map.put("startId", new Integer(startId));
	    map.put("endId", new Integer(startId+pageSize));
	    List list = messageDao.getMessageList(map);
	    PageModel pageModel = new PageModel();
	    pageModel.setList(list);
	    pageModel.setCurrentPage(page);
	    pageModel.setPageSize(pageSize);
	    
	    int count = messageDao.getMessageListCount(map);
	    pageModel.setTotalRecord(count);
	    pageModel.setTotalPage((int)Math.ceil((double)count/pageSize));
	    return pageModel;
	}
	
	public PageModel getMsgReceiveBox(Member member,int page){
		if(member == null) return null;
		int pageSize = 13;
	    Map map = new HashMap();
	    map.put("type",new Integer(Constants.MSG_TYPE_SHORT));
	    map.put("boxType", new Integer(Constants.MSG_BOX_RECEIVE));
	    map.put("member", member.getId());
	    int startId = (page-1) * pageSize + 1; 
	    map.put("startId", new Integer(startId));
	    map.put("endId", new Integer(startId+pageSize));
	    List list = messageDao.getMessageList(map);
	    PageModel pageModel = new PageModel();
	    pageModel.setList(list);
	    pageModel.setCurrentPage(page);
	    pageModel.setPageSize(pageSize);
	    
	    int count = messageDao.getMessageListCount(map);
	    pageModel.setTotalRecord(count);
	    pageModel.setTotalPage((int)Math.ceil((double)count/pageSize));
	    return pageModel;
	}
	
	public PageModel getMailSendBox(Member member,int page){
		if(member == null) return null;
		int pageSize = 13;
	    Map map = new HashMap();
	    map.put("type",new Integer(Constants.MSG_TYPE_EMAIL));
	    map.put("boxType", new Integer(Constants.MSG_BOX_SEND));
	    map.put("member", member.getId());
	    int startId = (page-1) * pageSize + 1; 
	    map.put("startId", new Integer(startId));
	    map.put("endId", new Integer(startId+pageSize));
	    List list = messageDao.getMessageList(map);
	    PageModel pageModel = new PageModel();
	    pageModel.setList(list);
	    pageModel.setCurrentPage(page);
	    pageModel.setPageSize(pageSize);
	    
	    int count = messageDao.getMessageListCount(map);
	    pageModel.setTotalRecord(count);
	    pageModel.setTotalPage((int)Math.ceil((double)count/pageSize));
	    return pageModel;
	}
	
	public PageModel getMsgSendBox(Member member,int page){
		if(member == null) return null;
		int pageSize = 13;
	    Map map = new HashMap();
	    map.put("type",new Integer(Constants.MSG_TYPE_SHORT));
	    map.put("boxType", new Integer(Constants.MSG_BOX_SEND));
	    map.put("member", member.getId());
	    int startId = (page-1) * pageSize + 1; 
	    map.put("startId", new Integer(startId));
	    map.put("endId", new Integer(startId+pageSize));
	    List list = messageDao.getMessageList(map);
	    PageModel pageModel = new PageModel();
	    pageModel.setList(list);
	    pageModel.setCurrentPage(page);
	    pageModel.setPageSize(pageSize);
	    
	    int count = messageDao.getMessageListCount(map);
	    pageModel.setTotalRecord(count);
	    pageModel.setTotalPage((int)Math.ceil((double)count/pageSize));
	    return pageModel;
	}
	
	public Message getMessageById(String id){
		if(StringUtils.isEmpty(id)) return null;
		Map map = new HashMap();
	    map.put("id",id);
	    List list = messageDao.getMessageList(map);
	    if(list != null && list.size() > 0 ){
	    	Message msg = (Message) list.get(0);
	    	List attachList = newsService.getAttachList(msg.getId(), Constants.BELONG_TYPE_MSG);
	    	msg.setAttachList(attachList);
	    	return msg;
	    }
	    	
		return null;
	}
	
	public List getMessageList(){
		Map map = new HashMap();
		map.put("startId", new Integer(0));
		map.put("endId", new Integer(1000));
		return messageDao.getMessageList(map);
	}
	
	public void readMessage(String id){
		Message msg = new Message();
		msg.setId(id);
		msg.setIsRead(new Boolean(true));
		messageDao.updateMessage(msg);
	}
	
	public int getNoReadEmail(Member member){
		if(member == null)return 0;
		Map map = new HashMap();
		map.put("type",new Integer(Constants.MSG_TYPE_EMAIL));
	    map.put("boxType", new Integer(Constants.MSG_BOX_RECEIVE));
	    map.put("isRead",new Boolean(false));
	    map.put("member",member.getId());
		return messageDao.getMessageListCount(map);
	}
	
	public int getNoReadMsg(Member member){
		if(member == null)return 0;
		Map map = new HashMap();
		map.put("type",new Integer(Constants.MSG_TYPE_SHORT));
	    map.put("boxType", new Integer(Constants.MSG_BOX_RECEIVE));
	    map.put("isRead",new Boolean(false));
		return messageDao.getMessageListCount(map);
	}
	
	public List getIndexShort(Member member){
	    if(member == null)return null;
	    Map map = new HashMap();
	    map.put("type",new Integer(Constants.MSG_TYPE_SHORT));
	    map.put("boxType", new Integer(Constants.MSG_BOX_RECEIVE));
	    map.put("member", member.getId());
	    map.put("startId", new Integer(1));
	    map.put("endId", new Integer(5));
	    return messageDao.getMessageList(map);
	}
	
	public void saveMessage(Message message){
		messageDao.insertMessage(message);
	}
	
	public boolean sendMail(Member member,Message message){
		return sendMail(member, message, false);
	}
	
	public boolean sendMail(final Member member,final Message message,final boolean isResend){
		try{
			ts.startTransaction(); 
			if(message != null){ 
				final String exsitId = message.getId();
				message.setIsRead(new Boolean(false));
				message.setSendStatus(new Boolean(true));
				String rmember = message.getRmember(); 
				if(!StringUtils.isEmpty(rmember)){
					
					Integer id = idService.generateId(Constants.TABLE_MESSAGE);
					message.setId(String.valueOf(id));
					message.setType(new Integer(Constants.MSG_TYPE_EMAIL));
					message.setSmember(member.getId());
//					自己发件箱先保留发送的邮件
					message.setBoxType(new Integer(Constants.MSG_BOX_SEND));
					message.setMember(member.getId());
					messageDao.insertMessage(message);
//					同时如果要求给自己也发送一条短信的话
					if(Constants.SEND_BACK){
						Helper.sendShortMsg(member.getMobile(), member.getUsername()+":"+message.getTitle());
					}
					
					String attachs = message.getAttachs();
					JSONArray attachList = null;
					if(!StringUtils.isEmpty(attachs)){
						attachList = JSONArray.fromObject(attachs);
					}
					//是否是重发信息
					if(!isResend){
						if(attachList != null && attachList.size() > 0){
							for (int j = 0; j < attachList.size(); j++) {
								JSONObject obj = attachList.getJSONObject(j);
								Attach attach = (Attach) JSONObject.toBean(obj, Attach.class);
								attach.setBelongId(String.valueOf(id));
								attach.setBelongType(new Integer(Constants.BELONG_TYPE_MSG));
								attach.setId(String.valueOf(idService.generateId(Constants.TABLE_ATTACH)));
								newsService.insertAttach(attach);
							}
							
						}
					}else{
						List attachss = newsService.getAttachList(exsitId, Constants.BELONG_TYPE_MSG);
						if(attachss != null && attachss.size() > 0){
							for (int j = 0; j < attachss.size(); j++) {
								Attach attach = (Attach) attachss.get(j);
								attach.setId(String.valueOf(idService.generateId(Constants.TABLE_ATTACH)));
								attach.setBelongId(String.valueOf(id));
								newsService.insertAttach(attach);
							}
						}
					}
					
//					发送给所有人的收件箱的邮件
				//	String[] rmembers = rmember.split(";"); 
					final JSONArray attachListTread = attachList;
					final Set memberSet = getRmembers(rmember);
					new Thread(new Runnable(){

						public void run() {
							
							Iterator it = memberSet.iterator();  
							while (it.hasNext()) {  
							  String msgMember = (String) it.next();  
							  if(!msgMember.equals(member.getId())){
								  	String rid = String.valueOf(idService.generateId(Constants.TABLE_MESSAGE));
									message.setId(rid);
									message.setBoxType(new Integer(Constants.MSG_BOX_RECEIVE));
									message.setMember(msgMember);
									messageDao.insertMessage(message);

//									附件
									//是否是重发信息
									if(!isResend){
										if(attachListTread != null && attachListTread.size() > 0){ 
											for (int j = 0; j < attachListTread.size(); j++) {
												JSONObject obj = attachListTread.getJSONObject(j);
												Attach attach = (Attach) JSONObject.toBean(obj, Attach.class);
												attach.setBelongId(rid);
												attach.setBelongType(new Integer(Constants.BELONG_TYPE_MSG));
												attach.setId(String.valueOf(idService.generateId(Constants.TABLE_ATTACH)));
												newsService.insertAttach(attach);
											}
											
										}
									}else{
										List attachss = newsService.getAttachList(exsitId, Constants.BELONG_TYPE_MSG);
										if(attachss != null && attachss.size() > 0){
											for (int j = 0; j < attachss.size(); j++) {
												Attach attach = (Attach) attachss.get(j);
												attach.setId(String.valueOf(idService.generateId(Constants.TABLE_ATTACH)));
												attach.setBelongId(rid);
												newsService.insertAttach(attach);
											}
										}
									}
//									如果短信通知要发送短信
									if(message.getIsSendMsg() != null && message.getIsSendMsg().booleanValue()){
										Member smsMember = memberService.getMemberById(msgMember);
										if(smsMember != null){
											Helper.sendShortMsg(smsMember.getMobile(), message.getTitle());
										}
									}
									
							  }
							 
								
							}
						}
						
					}).start();
					
					  
					/*
					for (int i = 0; i < rmembers.length; i++) {
						String rmdet = rmembers[i];
						String msgMember = null;
						if(rmdet.startsWith("(") && rmdet.endsWith(")")){
							String[] rmdets = rmdet.replaceAll("\\(", "").replaceAll("\\)", "").split(",");
							msgMember = rmdets[0];
						}else{
							msgMember = rmembers[i];
						}
						
						String rid = String.valueOf(idService.generateId(Constants.TABLE_MESSAGE));
						message.setId(rid);
						message.setBoxType(new Integer(Constants.MSG_BOX_RECEIVE));
						message.setMember(msgMember);
						messageDao.insertMessage(message);

//						附件
						//是否是重发信息
						if(!isResend){
							if(attachList != null && attachList.size() > 0){ 
								for (int j = 0; j < attachList.size(); j++) {
									JSONObject obj = attachList.getJSONObject(j);
									Attach attach = (Attach) JSONObject.toBean(obj, Attach.class);
									attach.setBelongId(rid);
									attach.setBelongType(new Integer(Constants.BELONG_TYPE_MSG));
									attach.setId(String.valueOf(idService.generateId(Constants.TABLE_ATTACH)));
									newsService.insertAttach(attach);
								}
								
							}
						}else{
							List attachss = newsService.getAttachList(exsitId, Constants.BELONG_TYPE_MSG);
							if(attachss != null && attachss.size() > 0){
								for (int j = 0; j < attachss.size(); j++) {
									Attach attach = (Attach) attachss.get(j);
									attach.setId(String.valueOf(idService.generateId(Constants.TABLE_ATTACH)));
									attach.setBelongId(rid);
									newsService.insertAttach(attach);
								}
							}
						}
						
					}
					
					*/
				}
				
//				如果短信通知要发送短信
			/*	if(message.getIsSendMsg() != null && message.getIsSendMsg().booleanValue()){
					message.setContent(message.getTitle());
					sendMsg(member, message,false);
				}*/
			}
			ts.commitTransAction();
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			try {
				ts.endTransAction();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		
		return true;
	}
	
	public Set getRmembers(String rmember){
		if(StringUtils.isEmpty(rmember)){
			return null;
		}
		Set members = new HashSet();
		String[] rmembers = rmember.split(";");
		for (int i = 0; i < rmembers.length; i++) {
			String member = rmembers[i];
			String[] memberObj = member.split("#");
			String id = memberObj[0];
			String type = memberObj[1];
		//	String name = memberObj[2];
			if("P".equals(type)){
				members.add(id);
			}else if("G".equals(type)){
				List memberList = memberService.getMemberByRole(id);
				if(memberList != null && memberList.size() > 0){
					for (int j = 0; j < memberList.size(); j++) {
						Member gmember = (Member) memberList.get(j);
						members.add(gmember.getId());
					}
				}
				List sonRoleList = memberService.getRoleByParent(id);
				if(sonRoleList != null && sonRoleList.size() > 0){
					for (int k = 0; k < sonRoleList.size(); k++) {
						Role sonRole = (Role) sonRoleList.get(k);
						List memberList2 = memberService.getMemberByRole(sonRole.getId());
						if(memberList2 != null && memberList2.size() > 0){
							for (int j = 0; j < memberList2.size(); j++) {
								Member gmember = (Member) memberList2.get(j);
								members.add(gmember.getId());
							}
						}
						List sonSonRoleList = memberService.getRoleByParent(sonRole.getId());
						if(sonSonRoleList != null && sonSonRoleList.size() > 0){
							for (int m = 0; m < memberObj.length; m++) {
								Role sonSonRole = (Role) sonSonRoleList.get(m);
								List memberList3 = memberService.getMemberByRole(sonSonRole.getId());
								if(memberList3 != null && memberList3.size() > 0){
									for (int j = 0; j < memberList3.size(); j++) {
										Member gmember = (Member) memberList3.get(j);
										members.add(gmember.getId());
									}
								}
							}
							
						}
					}
					
				}
			}
		}
		
		
		return members;
	}
	
	public boolean sendMsg(final Member member,final Message message,final boolean isMsg){
		try{
			ts.startTransaction();  
			if(message != null){ 
				Date now = new Date();
				message.setCreateDate(now);
				message.setModifyDate(now);
				message.setIsRead(new Boolean(false));
				message.setSendStatus(new Boolean(true));
				String rmember = message.getRmember(); 
				if(!StringUtils.isEmpty(rmember)){
					message.setType(new Integer(Constants.MSG_TYPE_SHORT));
					message.setSmember(member.getId());
							
					
//					发送给所有人的短信
					final Set memberSet = getRmembers(rmember);
					new Thread(new Runnable(){

						public void run() {
							boolean status = false;
							Iterator it = memberSet.iterator();  
							while (it.hasNext()) {
							  String memberId = (String) it.next();  
							  Member receiveMember = memberService.getMemberById(memberId);
		                      String receiveMobile = receiveMember.getMobile();
//		                     短信日志里是否已经存在发送给对方的记录
		                      Map map = new HashMap();
		                      map.put("sendMobile", member.getMobile());
		                      map.put("receiveMobile", receiveMobile);
		                      List smsList = messageDao.getSmsList(map);
		                      String numTag = null;
		                      if(smsList != null && smsList.size() > 0){
		                      	numTag = ((Sms)smsList.get(0)).getNumTag();
		                      }else{
		                      	numTag = Helper.getNumTag();
		                      }
		                      status = Helper.sendShortMsg(receiveMobile, member.getUsername()+":"+message.getContent(),numTag);
//		                      如果是发送短信同时也要发送到自己的手机
		                     /* if(isMsg && Constants.SEND_BACK){
		                      	Helper.sendShortMsg(member.getMobile(), member.getUsername()+":"+message.getContent());
		                      }*/
//		                          如果短信发送成功则同时发送信息到对方的收件箱
		                //      if(status){
		                      	String rid = String.valueOf(idService.generateId(Constants.TABLE_MESSAGE));
		                          message.setId(rid);
		                          message.setBoxType(new Integer(Constants.MSG_BOX_RECEIVE));
		                          message.setMember(memberId);
		                          messageDao.insertMessage(message);
//		                        同时保留短信号码的日志
		                          Sms sms = null;
		                          if(smsList != null && smsList.size() > 0){
		                          	sms = (Sms) smsList.get(0);
		                          }else{
		                          	sms = new Sms();
		                          	sms.setSendMobile(member.getMobile());
		                          	sms.setReceiveMobile(receiveMobile);
		                          	sms.setNumTag(numTag);
		                          }
		                          saveSms(sms);	
//								}
							}
//	    					自己发件箱保留短信到发件箱
	                        Integer id = idService.generateId(Constants.TABLE_MESSAGE);
	                        message.setId(String.valueOf(id));
	    					message.setBoxType(new Integer(Constants.MSG_BOX_SEND));
	    					message.setMember(member.getId());
	    					message.setSendStatus(new Boolean(status));
	    					messageDao.insertMessage(message);
						}
						
					}).start();
					
					
					/*
					String[] rmembers = rmember.split(";");
					
                    for (int j = 0; j < rmembers.length; j++) {
                    	String rmdet = rmembers[j];
						String memberId = null;
						String type = null;
						if(rmdet.startsWith("(") && rmdet.endsWith(")")){
							String[] rmdets = rmdet.replaceAll("\\(", "").replaceAll("\\)", "").split(",");
							memberId = rmdets[0];
							type = rmdets[1];
						}else{
							type = "手机";
						}
						
                        
//                      如果是网站用户
                        if(type.equals("网站")){
                            Member receiveMember = memberService.getMemberById(memberId);
                            String receiveMobile = receiveMember.getMobile();
//                           短信日志里是否已经存在发送给对方的记录
                            Map map = new HashMap();
                            map.put("sendMobile", member.getMobile());
                            map.put("receiveMobile", receiveMobile);
                            List smsList = messageDao.getSmsList(map);
                            String numTag = null;
                            if(smsList != null && smsList.size() > 0){
                            	numTag = ((Sms)smsList.get(0)).getNumTag();
                            }else{
                            	numTag = Helper.getNumTag();
                            }
                            status = Helper.sendShortMsg(receiveMobile, member.getUsername()+":"+message.getContent(),numTag);
//                            如果是发送短信同时也要发送到自己的手机
                            if(isMsg && Constants.SEND_BACK){
                            	Helper.sendShortMsg(member.getMobile(), member.getUsername()+":"+message.getContent());
                            }
//                                如果短信发送成功则同时发送信息到对方的收件箱
                      //      if(status){
                            	String rid = String.valueOf(idService.generateId(Constants.TABLE_MESSAGE));
                                message.setId(rid);
                                message.setBoxType(new Integer(Constants.MSG_BOX_RECEIVE));
                                message.setMember(memberId);
                                messageDao.insertMessage(message);
//                              同时保留短信号码的日志
                                Sms sms = null;
                                if(smsList != null && smsList.size() > 0){
                                	sms = (Sms) smsList.get(0);
                                }else{
                                	sms = new Sms();
                                	sms.setSendMobile(member.getMobile());
                                	sms.setReceiveMobile(receiveMobile);
                                	sms.setNumTag(numTag);
                                }
                                saveSms(sms);	
                        //    }

                            
                        }else if(type.equals("通讯录")){//通讯录用户
                        	Contacts contacts = memberService.getContactById(memberId);
                            String mobile = contacts.getMobile();
                        	status = Helper.sendShortMsg(mobile, message.getContent());
                        }else if(type.equals("手机")){//直接输入手机号
                            status = Helper.sendShortMsg(memberId, message.getContent());
                        }
                        
                    }
                    */


               }
				
				
			}
			ts.commitTransAction();
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}finally{
			try {
				ts.endTransAction();
			} catch (SQLException e1) {
				e1.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	
	
	public void deleteMessage(String id){
	    if(StringUtils.isEmpty(id))return ;
	    Map map = new HashMap();
	    map.put("id", id);
	    messageDao.deleteMessage(map);
	}
	
	public List getSmsList(String fromMobile,String numTag){
		Map map = new HashMap();
		map.put("receivemobile", fromMobile);
		map.put("numTag", numTag);
		return messageDao.getSmsList(map);
	}
	public void saveSms(Sms sms){
		if(sms == null) return ;
		Date now = new Date();
		sms.setUpdateTime(now);
		if(StringUtils.isEmpty(sms.getId())){
			sms.setId(String.valueOf(idService.generateId(Constants.TABLE_SMS)));
			sms.setCreateTime(now);
			messageDao.insertSms(sms);
		}else{
			messageDao.updateSms(sms);
		}
			
	}
	
	public void deleteSms(){
		messageDao.deleteSms(null);
	}
	
	public static void main(String[] args){
		MessageService service = new MessageService();
//		System.out.println(service.sendShortMsg("13564369099", "我又发信息了？？"));
		Member member = new Member();
		member.setId("1");
		Message message = new Message();
		message.setRmember("1");
		message.setTitle("test");
		message.setContent("xxxxx");
		message.setAttachs("[{\"1\"},{\"2\"}]");
//		service.sendMail(member, message,false);
		Set set = service.getRmembers("feixiang#P#飞翔;yulong2#P#于龙;admin#P#admin;1#G#招办通讯录;");
		System.out.println(set);
	}

}
